package com.nanhang.controller;

import cn.hutool.db.sql.Order;
import com.nanhang.common.util.PageResult;
import com.nanhang.common.util.R;
import com.nanhang.entity.User;
import com.nanhang.request.UaORequest;
import com.nanhang.service.UserService;
import com.nanhang.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/list")
    public R findAll(){
        List<User> list = userService.list();
        return R.ok().data("list",list);
    }
    // 分页查询
    @GetMapping("/findByPage/{page}/{pageSize}")
    public R findByPage(@PathVariable("page") Integer page,
                        @PathVariable("pageSize") Integer pageSize) {
        PageResult<User> pr = userService.findByPage(page,pageSize);
        return R.ok().data("pr",pr);
    }
    //条件分页查询
    @PostMapping("/search/{page}/{pageSize}")
    public R search(@PathVariable("page") Integer page,
                    @PathVariable("pageSize") Integer pageSize,
                    @RequestBody(required = false) UserVo vo){
        PageResult<User> pr = userService.search(page,pageSize,vo);
        return R.ok().data("pr",pr);
    }
    //删除
    @DeleteMapping("/delete/{ids}")
    public R delete(@PathVariable("ids") String ids){  // 1,2,3
        String[] split = ids.split(",");
        List<String> uids = Arrays.asList(split);
        return userService.removeByIds(uids) ? R.ok().message("删除用户成功!") : R.error().message("删除用户失败!");
    }
    //修改
    @PutMapping("/update")
    public R update(@RequestBody User user){
        boolean flag =userService.updateById(user);
        return flag ? R.ok().message("修改用户成功!") : R.error().message("修改用户失败!");
    }
    //添加
    @PostMapping("/add")
    public R add(@RequestBody User user){
        boolean flag = userService.add(user);
        return flag ? R.ok().message("添加用户成功!") : R.error().message("添加用户失败!");
    }
    // 添加用户和添加订单的接口
    @PostMapping("/addUserWithOrder")
    public R addUserWithOrder(@RequestBody UaORequest uaORequest) {
        //获取用户和订单信息
        User user = uaORequest.getUser();
        Order order = uaORequest.getOrder();
        String response = userService.addUserWithOrder(user, order);
        return R.ok().message(response);
    }
}
